package service.file;

import java.io.File;
import java.util.List;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import base.service.IBaseService;
import entity.file.FileName;
import entity.file.MyFile;

@Service("fileServiceImpl")
public class FileServiceImpl implements IFileService {

	@Resource
	private IBaseService baseServiceImpl;

	@Override
	public MyFile getFileByMd5Value(String md5Value, double size, String type) throws Exception {
		// TODO Auto-generated method stub
		MyFile myFile = baseServiceImpl.findOne("from MyFile where md5value = ? and size = ? and type = ?",
				new Object[] { md5Value, size, type });
		return myFile;
	}

	@Override
	public MyFile saveFile(MultipartFile file,String path,String md5Value) throws Exception {
		// TODO Auto-generated method stub
		File localFile = new File(path);
		file.transferTo(localFile);
		// 新建MyFile文件对象
		MyFile myFile = new MyFile();
		myFile.setMd5value(md5Value);
		myFile.setPath(path);
		myFile.setSize(file.getSize());
		myFile.setType(file.getContentType());
		myFile = baseServiceImpl.save(myFile);
		return myFile;
	}

	@Override
	public List<MyFile> saveMyFiles(List<MyFile> myFiles) throws Exception {
		// TODO Auto-generated method stub
		myFiles = baseServiceImpl.save(myFiles);
		return myFiles;
	}

	@Override
	public MyFile getMyFileById(String id) throws Exception {
		// TODO Auto-generated method stub
		return baseServiceImpl.getById(MyFile.class, id);
	}

	@Override
	public void useFileName(FileName fileName) throws Exception {
		// TODO Auto-generated method stub
		baseServiceImpl.saveOrUpdate(fileName);
		MyFile myFile = fileName.getMyFile();
		myFile.setUsetimes(myFile.getUsetimes() + 1);
		baseServiceImpl.saveOrUpdate(myFile);
	}

	@Override
	public void unUseFileName(FileName fileName) throws Exception {
		// TODO Auto-generated method stub
		MyFile myFile = fileName.getMyFile();
		int userTimes = myFile.getUsetimes() - 1;
		if (userTimes == 0) {
			File localFile = new File(myFile.getPath());
			localFile.deleteOnExit();
			baseServiceImpl.delete(myFile);
		} else {
			myFile.setUsetimes(userTimes);
			baseServiceImpl.saveOrUpdate(myFile);
		}
		baseServiceImpl.delete(fileName);
	}

	@Override
	public FileName getFileNameById(String id) throws Exception {
		// TODO Auto-generated method stub
		return baseServiceImpl.getById(FileName.class, id);
	}

}
